package top.yehot.cmmu.swagger.support;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;

import lombok.RequiredArgsConstructor;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import top.yehot.cmmu.swagger.config.SwaggerProperties;

@Primary
@RequiredArgsConstructor
public class SwaggerProvider implements SwaggerResourcesProvider {

	private static final String API_URI = "/v2/api-docs";
	
	private final SwaggerProperties swaggerProperties;
	
	@Lazy
	@Autowired
	private RouteLocator routeLocator;

	@Override
	public List<SwaggerResource> get() {
		// 接口资源列表
		List<SwaggerResource> resources = new ArrayList<SwaggerResource>();
		
		// 服务名称列表
		List<String> routes = new ArrayList<String>();
		// 获取所有可用的应用名称
		routeLocator.getRoutes().subscribe(route -> routes.add(route.getUri().getHost()));
		// 去重，多负载服务只添加一次
		List<String> newRoutes = routes.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(a -> a))), ArrayList::new));
		
		newRoutes.stream().filter(host -> !swaggerProperties.getIgnoreProviders().contains(host))
			.forEach(host -> resources.add(swaggerResource(host, "/" + host + API_URI)));
		return resources;
	}

	private SwaggerResource swaggerResource(String name, String location) {
		String newName = swaggerProperties.getServices().get(name);
		name = (null == newName || "".equals(newName.trim()) ? name : newName);
		
		SwaggerResource swaggerResource = new SwaggerResource();
		swaggerResource.setName(name);
		swaggerResource.setLocation(location);
		swaggerResource.setSwaggerVersion("2.0");
		return swaggerResource;
	}

}
